﻿using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QiNiuStorage
{
    /// <summary>
    /// //NuGet引用： Qiniu(8.3.1)
    /// 七牛云存储官网：  https://www.qiniu.com/products/kodo
    /// 七牛云存储空间管理：  https://portal.qiniu.com/kodo/bucket   !!!!! 切记：设置为：公开空间
    /// c#参考官网文档：  https://developer.qiniu.com/kodo/1237/csharp   /  https://developer.qiniu.com/kodo/1500/csharp-sdk-v7p0
    /// </summary>
    public class QiNiuHelper
    {
        //string filePath        UploadFile(filePath
        //byte[] data            UploadData(data
        //FileStream fs          UploadStream(fs
        //MemoryStream           UploadStream(fs

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云上传普通文件
        /// </summary>
        public static string QiNiuUploadFile(string tmpFileName)
        {
            //请到官网申请七牛云账号、秘钥(申请位置：点击头像，秘钥管理)
            //var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            //var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";
            var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";



            //保存到七牛云上的文件目录
            //var tmpFileName = "44.jpg";// "11.doc";// "44.jpg";
            var tmpUrl = "mywork/images/" + tmpFileName; //上传到七牛云的地址目录，注意: /
            // 文件所在本地文件路径 
            string filePath = "D:\\专高六\\项目\\爱吃兔溯源1.08\\完整\\Rabbit\\Business.ReadAPI\\wwwroot\\img\\" + tmpFileName; 
            // 存储空间名
            string Bucket = "zbitter";
            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略有效期(对应于生成的凭证的有效期，单位:秒)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            // 生成上传token
            Mac mac = new Mac(accessKey, secretKey);
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Config config = new Config();
            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_East;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            // 表单上传
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadFile(filePath, tmpUrl, token, null);
            Console.WriteLine("返回结果： " + result.ToString());

            //var qiniuResult = JsonConvert.DeserializeObject<UploadQiNiuResult>(result.Text);
            var imgUrl = "http://snadnmofg.hb-bkt.clouddn.com/" + tmpUrl;
            //http://sna5j5bfp.hb-bkt.clouddn.com/myimages/students/%E5%A4%8F%E8%8A%B1.jpg
            Console.WriteLine(imgUrl);
            return imgUrl;
        }

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云上传节流数据
        /// </summary>
        public static void QiNiuUploadByteData()
        {
            
            //请到官网申请七牛云账号、秘钥
            var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";

            Mac mac = new Mac(accessKey, secretKey);
            //保存到七牛云上的文件目录
            string saveKey = "mywork/images/66.jpg"; //注意: /
            // 本地文件路径
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "images\\66.jpg";  // 注意: //
            //byte[] data = System.IO.File.ReadAllBytes("D:/QFL/1.mp3");
            byte[] data = File.ReadAllBytes(filePath);

            // 存储空间名
            string Bucket = "zlf8";
            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略的过期时间(单位:秒)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            // 生成上传token
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Config config = new Config();
            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_South;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            // 表单上传
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadData(data, saveKey, token, null);
            Console.WriteLine("返回结果： " + result.ToString());

            var imgUrl = "http://sna74ffg2.hb-bkt.clouddn.com/\r\n" + saveKey;
            Console.WriteLine(imgUrl);
        }

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云上传数据流
        /// </summary>
        public static void QiNiuUploadStream()
        {
            //请到官网申请七牛云账号、秘钥
            var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";

            Mac mac = new Mac(accessKey, secretKey);
            //保存到七牛云上的文件目录
            string saveKey = "mywork/images/ren3.jpg";

            // 本地文件路径
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "images\\ren3.jpg";
            FileStream fs = new FileStream(filePath, FileMode.Open);

            // 存储空间名
            string Bucket = "zlf8";
            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            // 设置要上传的目标空间
            putPolicy.Scope = Bucket;

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;

            // 上传策略的过期时间(单位:秒)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
            putPolicy.DeleteAfterDays = 100;

            // 生成上传token
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

            Config config = new Config();
            // 设置上传区域  [CN_East:华东] [CN_South:华南] [CN_North:华北] [US_North:北美]
            config.Zone = Zone.ZONE_CN_North;
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            // 数据流上传
            FormUploader fu = new FormUploader(config);
            //七牛云支持 stream流、MemoryStream流、Filestream流上传
            var result = fu.UploadStream(fs, saveKey, token, null);
            fs.Dispose();
            Console.WriteLine(result);

            var imgUrl = "http://sna74ffg2.hb-bkt.clouddn.com/\r\n" + saveKey;
            Console.WriteLine(imgUrl);
        }

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云删除文件
        /// </summary>
        public static void QiNiuDeleteFile()
        {
            //请到官网申请七牛云账号、秘钥
            var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";

            // 存储空间名
            string Bucket = "zlf8";

            //保存到七牛云上的文件目录
            //string saveKey = "images/44.jpg";
            var saveKey = "mywork/images/66.jpg";

            //设置上传区域
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_East;//ZONE_CN_North
            Mac mac = new Mac(accessKey, secretKey);

            BucketManager bucketManager = new BucketManager(mac, config);
            HttpResult deleteRet = bucketManager.Delete(Bucket, saveKey);
            if (deleteRet.Code == (int)HttpCode.OK)
            {
                Console.WriteLine("删除成功： " + deleteRet.ToString());
            }
            else
            {
                Console.WriteLine("删除失败： " + deleteRet.ToString());
            }

            Console.WriteLine(deleteRet);
        }

        /// <summary>
        /// NuGet引用： Qiniu(8.3.1)
        /// 七牛云批量删除
        /// </summary>
        public static void QiNiuBatchDelete()
        {
            //请到官网申请七牛云账号、秘钥
            var accessKey = "eNYsMVDvsTgyVUS6H2PnTvfk_QEyNVmsHsSbzrjg";
            var secretKey = "eGsnWd3kIwH1MvFRjRwH4HxDWnTe9dvIqQrAaHja";

            // 存储空间名
            string Bucket = "zlf8";

            //设置上传区域
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_East;
            Mac mac = new Mac(accessKey, secretKey);
            BucketManager bucketManager = new BucketManager(mac, config);

            //设置要删除的文件数组
            string[] keys = {
                "myimages/students/夏花.jpg",
                "myimages/students/大熊猫.jpg"
            };

            List<string> ops = new List<string>();
            foreach (string key in keys)
            {
                string op = bucketManager.DeleteOp(Bucket, key);
                ops.Add(op);
            }

            BatchResult ret = bucketManager.Batch(ops);
            if (ret.Code / 100 != 2)
            {
                Console.WriteLine("批量删除报错: " + ret.ToString());
            }
            foreach (BatchInfo info in ret.Result)
            {
                if (info.Code == (int)HttpCode.OK)
                {
                    Console.WriteLine("批量删除成功 ");
                }
                else
                {
                    Console.WriteLine(info.Data.Error);
                }
            }
        }

    }
}
